﻿using AgencyManagerSystem.AsmType;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Model;
using System;
using System.Collections.Generic;

namespace AgencyManagerSystem.Core
{
    public abstract class DocManager<T> where T:DBModel
    {
        private BaseUpdater<T> updater;
        public DocManager()
        {
            updater = InjectionUpdater();
        }
        protected abstract BaseUpdater<T> InjectionUpdater();
        public virtual AsmObject<T> Set(T model)
        {
            string message;
            int result = updater.Save(model, out message);
            if (result == 0)
            {
                DBHelper.Commit(false);
                return new AsmObject<T>() { Message = message, Result = AmsCode.InnError };
            }
            else
            {
                return new AsmObject<T>() { Message = "操作成功", Result = AmsCode.Succ, Data = model };
            }
        }
        public virtual AsmObject<bool> Delete(T model)
        {
            string message;
            bool result = updater.Delete(model.AutoId, out message);
            if (!result)
            {
                DBHelper.Commit(false);
                return new AsmObject<bool>() { Message = message, Result = AmsCode.InnError, Data = false };
            }
            else
            {
                return new AsmObject<bool>() { Message = "操作成功", Result = AmsCode.Succ, Data = true };
            }
        }

        public virtual AsmArray<T> SetList(IEnumerable<T> models)
        {
            string message;
            int autoId;
            foreach (T model in models)
            {
                autoId = updater.Save(model, out message);
                if (autoId == 0)
                {
                    DBHelper.Commit(false);
                    return new AsmArray<T>() { Message = message, Result = AmsCode.InnError };
                }
            }
            return new AsmArray<T>() { Message = "操作成功", Result = AmsCode.Succ, Data = models };
        }
        public virtual AsmObject<bool> DeleteList(IEnumerable<T> models)
        {
            string message;
            foreach (T model in models)
            {
                bool effect = updater.Delete(model, out message);
                if (!effect)
                {
                    DBHelper.Commit(false);
                    return new AsmObject<bool>() { Message = message, Result = AmsCode.InnError, Data = false };
                }
            }
            return new AsmObject<bool> { Message = "操作成功", Result = AmsCode.Succ, Data = true };
        }
    }
}
